<?php

class ModAccount
{
	public function login()
	{
		if( !sessionLayer::getAccount() )
		{
			viewLayer::render('login'); //Load login form as view
			return true;
		}
	}
	
	private function toPassword( $str )
	{
		$passCryption = configParser::getData('passwordtype');
		
		switch( strtolower($passCryption) )
		{
			case "plain":
				return $str;
			case "sha1":
				return sha1($str);
			case "md5":
				return md5($str);
		}
	}
	
	public function index()
	{
		if( $this->login() ) return false;  //Load login form if user isn't logged in
		$Acc = new OTS_Account;
		$Acc->load( sessionLayer::getAccount() );

		$pList = array();
        foreach( $Acc as $Player )
        {
			$pList[] =  array( 'id' => $Player->getID(), 'name' => $Player->getName() );
        }
		
		viewLayer::$var->acc = array('no' => $Acc->getId(),'email' => $Acc->getEMail(), 'premium' => $Acc->getCustomField('premend'));
		viewLayer::$var->accChars = $pList;
		viewLayer::render('account');
	}
	
	public function recovery()
	{
		if( !$_POST['email'] )
		{
			viewLayer::render('recovery');
			return false;
		}
		
		$acc = new OTS_Account;
		$acc->find( $_POST['email'] );
		
		if( !$acc->isLoaded() )
		{
			viewLayer::render(NULL, 'There is not any account registered with this email.');
			viewLayer::render('recovery');
			return false;
		}
		$a1 = rand(3,13);
		$pass = substr(md5(time()), $a1, rand(5, 7) );
		$passCryption = configParser::getData('passwordtype');
		$acc->setPassword($this->toPassword($pass));
		
		$acc->save();
		
		
		if( mailLayer::send($acc, 'Account recovery', "Password:\n".$pass) ) {
			viewLayer::render(NULL, 'Check your email account for new password.');
		}
		else {
			viewLayer::render(NULL, 'Something in mailer is wrong, check your smtp configuration.');
			viewLayer::render('recovery');
		}
	}
	
	public function change_password()
	{
		if( $this->login() ) return false;	//Load login form if user isn't logged in
		//If form isn't complete load it.
		if( !$_POST['newPassword'] )
		{
			viewLayer::render('change_password');
			return false;
		}
		
		if( strlen($_POST['newPassword']) < 5 or strlen($_POST['newPassword']) > 15 )
		{
			viewLayer::render(NULL, 'Your new password length is not correct. Possible is only from 5 to 15 characters.');
		}
		
		//Check that new password is equal with confirm
		if( $_POST['confirmNewPassword'] == $_POST['newPassword'] )
		{
			if( $this->toPassword($_POST['password']) == sessionLayer::getPassword() ) //If old password pass
			{
				$acc = new OTS_Account;
				$acc->load( sessionLayer::getAccount() );
				$acc->password = $this->toPassword($_POST['newPassword']); //Set new password ( before hash it in sha1 )
				$acc->save();
				
				viewLayer::render(NULL, 'Password sucessfully changed.<br /><a href="?m=account">[Back to an account page]</a>');
			}
			else
			{
				viewLayer::render(NULL, 'You have not inserted correct password!');
			}
		}
		else
		{
			viewLayer::render(NULL, 'Are you sure that you repeated a new password correctly?');
		}
	}
	
	public function change_email()
	{
		if( $this->login() ) return false;	//Load login form if user isn't logged in
		
		if( !$_POST['newEmail'] )
		{
			viewLayer::render('change_email');
			return false;
		}
	
		if( $_POST['newEmail'] == $_POST['confirmNewEmail'] )
		{
			$Acc = new OTS_Account;
			$Acc->load( sessionLayer::getAccount() );
			
			if( $this->toPassword( $_POST['password'] ) == sessionLayer::getPassword() )
			{
				if( $Acc->eMail == $_POST['email'] )
				{
					$Acc->eMail = $_POST['email'];
					$Acc->save();
					
					viewLayer::render(NULL, 'Email successfully changed.<br /><a href="?m=account">[Back to an account page]</a>');
				}
				else
				{
					viewLayer::render(NULL, 'Old email adress is not valid.');
					viewLayer::render('change_email');
					return false;
				}
			}
			else
			{
				viewLayer::render(NULL, 'Password is not valid.');
				viewLayer::render('change_email');
				return false;
			}
		}
		else
		{
			viewLayer::render(NULL, 'New emails does not match.');
			viewLayer::render('change_email');
			return false;		
		}
	}
	
	public function delete_account()
	{
		if( $this->login() ) return false;	//Load login form if user isn't logged in
		
		if( !$_POST['password'] )
		{
			viewLayer::render('delete_account');
			return false;
		}
		
		if( $_POST['confirmed'] == 'yes' )
		{
			$Acc = new OTS_Account;
			$Acc->load( sessionLayer::getAccount() );
			
			if( $this->toPassword($_POST['password']) == sessionLayer::getPassword() )
			{
				sessionLayer::destroy();
				viewLayer::render(NULL, "Account {$Acc->id} is deleted successfully.<br /><br /><a href=\"?m=index\">[Back]</a>");
				$Acc->delete();
			}
			else
			{
				viewLayer::render(NULL, "Password is not valid.");
				viewLayer::render('delete_account');
				return false;
			}
		}
		
	}
	
	public function create_character()
	{
		if( $this->login() ) return false;	//Load login form if user isn't logged in
		
		if( !$_POST['name'] )
		{
			viewLayer::render('create_character');
			return false;
		}

		$sex = intval( $_POST['sex'] );
		$vocation = intval( $_POST['vocation'] );
		if( $sex > 1 or $sex < 0 or $vocation < 0 or $vocation > 4 )
		{
			viewLayer::render(NULL, 'You can\'t cheat here! :)');
			viewLayer::render('');
			return false;
		}
		
		if( configLayer::get('register_unallowed_names') )
		{
			foreach( explode(':', configLayer::get('register_unallowed_names')) as $name )
			{
				if( strpos($_POST['name'], $name) )
				{
					viewLayer::render('You have used an unallowed name, please correct it!');
					viewLayer::render('create_character');
					return false;
				}
			}
		}
		
		if( preg_match("/[a-zA-Z ']{1,25}/", $_POST['name']) )
		{
			$character = new OTS_Player;	
			$character->find( $_POST['name'] );
			if( $character->isLoaded() )
			{
				viewLayer::render(NULL, 'This name is already in use.');
				viewLayer::render('create_character');
				return false;
			}
			
			$acc = new OTS_Account;
			$acc->load( sessionLayer::getAccount() );
			$character->setAccount( $acc );
			$group = new OTS_Group;
			$group->load(1);
			$character->setGroup( $group );
			$character->setName( $_POST['name'] );
			$character->setVocation($vocation);
			$character->setSex($sex);
			POT::getInstance()->loadVocations( configParser::$confdir . configParser::getData('datadir') . 'XML/' . 'vocations.xml' );
			POT::getInstance()->loadSpells( configParser::$confdir . configParser::getData('datadir') . 'spells/spells.xml' );
			$schema = new OTS_Player;
			$schema->find(POT::getInstance()->getVocationName( $vocation) . " schema");
			if( !$schema->isLoaded() )
			{
				viewLayer::render( NULL, "AAC doesn't have schema characters to use. Please, contact with administrator.<br /><a href=\"?m=account\">[Back to an account page]</a>" );
				return false;
			}
			$character->setBalance( $schema->getBalance() );
			$character->setHealth( $schema->getHealth() );
			$character->setHealthMax( $schema->getHealthMax() );
			$character->setMana( $schema->getMana() );
			$character->setManaMax( $schema->getManaMax() );
			$character->setLevel( $schema->getLevel() );
			$character->setExperience( $schema->getExperience() );
			$character->setDirection( $schema->getDirection() );
			$character->setCap( $schema->getCap() );
			$character->setMagLevel( $schema->getMagLevel() );
			$character->setManaSpent( $schema->getManaSpent() );
			$character->setLossSkills( $schema->getLossSkills() );
			$character->setLossExperience( $schema->getLossExperience() );
			$character->setLossItems( $schema->getLossItems() );
			$character->setLossExperience( $schema->getLossExperience() );
			$character->setPosX( $schema->getPosX() );
			$character->setPosY( $schema->getPosY() );
			$character->setPosZ( $schema->getPosZ() );
			$character->setRedSkullTime( $schema->getRedSkullTime() );
			$character->setSoul( $schema->getSoul() );
			foreach( $schema->getSpellsList() as $Spell )
			{
				$character->addSpell( $Spell );
			}
			for( $i = 0; $i < POT::SKILL_FISHING; $i++ )
			{
				$character->setSkill( $i, $schema->getSkill( $i ) );
				$character->setSkillTries( $i, $schema->getSkillTries( $i ) );
			}
			$character->setTownId( configLayer::get('register_startup_town') );
			$character->setLookBody(128);
			$character->setLookHead(128);
			$character->setLookLegs(128);
			$character->setLookFeet(128);
			$character->setLookType( ($sex) ? 128 : 136 );
			$character->setSave( 1 );	
			$character->save();
			foreach( dbLayer::query( "SELECT * FROM `player_items` WHERE `player_id`={$schema->id};" )->fetchAll() as $Q )
			{
					dbLayer::query( "INSERT INTO `player_items`(`player_id`, `sid`, `pid`, `itemtype`, `count`, `attributes`) VALUES({$character->id}, {$Q['sid']}, {$Q['pid']}, {$Q['itemtype']}, {$Q['count']}, '${Q['attributes']}');" );
			}
			foreach( dbLayer::query( "SELECT * FROM `player_depotitems` WHERE `player_id`={$schema->id};" )->fetchAll() as $Q )
			{
					dbLayer::query( "INSERT INTO `player_depotitems`(`player_id`, `depot_id`, `sid`, `pid`, `itemtype`, `count`, `attributes`) VALUES({$character->id}, {$Q['depot_id']}, {$Q['sid']}, {$Q['pid']}, {$Q['itemtype']}, {$Q['count']}, '${Q['attributes']}');" );
			}
			dataLayer::savePlayerData( $character->id, time(), "", 0 );
			
			viewLayer::render(NULL, 'Character with name <strong>'.$_POST['name'].'</strong> is succesfully created.<br /><br /><strong>See you in ' . configParser::getData('worldname') . '!</strong><br /><br /><a href="?m=account">[Back to an account page]</a>');
		}
		else
		{
			viewLayer::render(NULL, 'Character name is not valid.');
			viewLayer::render('create_character');
			return false;
		}
	}
	
	public function register()
	{
		if( !$_POST['email'] )
		{
			viewLayer::render('register');
			return false;
		}
		
		if( !eregi("^[_.0-9a-z-]+@([0-9a-z][0-9a-z-]+.)+[a-z]{2,4}$" , $_POST['email']))
		{
			viewLayer::render(NULL, 'E-Mail adress is incorrect.');
			viewLayer::render('register');
			return false;
		}
		
		$acc = new OTS_Account;
		
		$acc->find( $_POST['email'] );
		if( $acc->isLoaded() ){
			viewLayer::render(NULL, 'Account with this e-mail already exists.');
			viewLayer::render('register');
			return false;
		}

		$pass = substr(md5(lcg_value()), 0, rand(5, 7) );
		
		$accno = $acc->create( 111111, 9999999 );
		$acc->password = $this->toPassword($pass);
		$acc->email = $_POST['email'];
		$acc->blocked = 0;
		$acc->save();
		
		if( mailLayer::send($acc, 'Account register', "Password:\n".$pass) ) {
			viewLayer::render(NULL, "<h1>Your account number is: $accno</h1>" . 'Account created successful! Please check your e-mail for the password.');
			return true;
		}
		else {
			viewLayer::render(NULL, 'Something in mailer is wrong, check your smtp configuration.');
			viewLayer::render('register');
			return false;
		}
		
	}
}
?>